from PIL import Image
from io import BytesIO
from hashlib import md5
from .ip_tool import get_host_ip
import os


class ImageTool:
    def __init__(self, width, height, folder, filename):
        self.width = width
        self.height = height
        self.folder = folder
        self.filename = filename

    def save_image(self, image, filename):
        if os.path.exists('static') is False:
            os.mkdir('static')
            os.mkdir('static/{}'.format(self.folder))
        elif os.path.exists('static/{}'.format(self.folder)) is False:
            os.mkdir('static/{}'.format(self.folder))
        image.save('./static/{}/{}'.format(self.folder, filename))

    def process_image(self, image_data):
        image = Image.open(BytesIO(image_data))
        w, h = image.size
        if w > self.width or h > self.height:
            w_scale = self.width / w
            h_scale = self.height / h
            if w_scale < h_scale:
                w = self.width
                h = w_scale * h
            else:
                h = self.height
                w = h_scale * w
            image.thumbnail((w, h))
        m = md5()
        m.update(self.filename.encode('utf-8'))
        filename = m.hexdigest() + '.jpeg'
        self.save_image(image, filename)
        return 'http://{}/{}/{}'.format(get_host_ip(), self.folder, filename)
